//
//  CLSearchCollectionViewFlowLayout.m
//  chanlin
//
//  Created by shuhui on 15-5-10.
//  Copyright (c) 2015年 chanlin. All rights reserved.
//

#import "CLSearchCollectionViewFlowLayout.h"

#define ITEM_SIZE 50


@implementation CLSearchCollectionViewFlowLayout
@synthesize cellCount;

- (void)prepareLayout{
    [super prepareLayout];
    cellCount=[self.collectionView numberOfItemsInSection:0];
}
-(CGSize)collectionViewContentSize{
    return [self collectionView].frame.size;
}

-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect{
    NSMutableArray* attributes = [NSMutableArray array];
    for (NSInteger i=0 ; i < self.cellCount; i++) {
        NSIndexPath* indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        [attributes addObject:[self layoutAttributesForItemAtIndexPath:indexPath]];
    }
    //从第二个循环到最后一个
    for(int i = 1; i < [attributes count]; ++i) {
        //当前attributes
        UICollectionViewLayoutAttributes *currentLayoutAttributes = attributes[i];
        //上一个attributes
        UICollectionViewLayoutAttributes *prevLayoutAttributes = attributes[i - 1];
        //设置的最大间距，可根据需要改
        NSInteger maximumSpacing = 10;
        //前一个cell的最右边
        NSInteger originX = CGRectGetMaxX(prevLayoutAttributes.frame);
        //前一个cell的最下边
        NSInteger originY = CGRectGetMaxY(prevLayoutAttributes.frame);
        //如果当前一个cell的最右边加上间距加上当前cell的宽度依然在contentSize中，改变当前cell的原点位置
        //不加这个判断的后果是，UICollectionView只显示一行，原因是下面所有cell的x值都被加到第一行最后一个元素的后面了
        if((originX + maximumSpacing + currentLayoutAttributes.frame.size.width) <= self.collectionViewContentSize.width) {
            CGRect frame = currentLayoutAttributes.frame;
            frame.origin.x = originX + maximumSpacing;
            frame.origin.y = originY - 32+0.5;
            currentLayoutAttributes.frame = frame;
        }
        else if(originX + maximumSpacing + currentLayoutAttributes.frame.size.width > self.collectionViewContentSize.width) {
            CGRect frame = currentLayoutAttributes.frame;
            frame.origin.x = 0;
            frame.origin.y = originY + maximumSpacing;
            currentLayoutAttributes.frame = frame;
        }
    }
    return attributes;
}
@end
